# Importing Data
BahrainNew <- read_excel("C:\Users\Biniam\Desktop\Documents\Academic\Thesis\Analysis Folder\R Files\BahrainNew\BahrainNew.xlsx")

# Checking the Imported Data
View(BahrainNew)
head(BahrainNew)
tail(BahrainNew)

# Creating Time Series Data
BahrainNew_ts <- ts(BahrainNew, start=c(2001,1), end=c(2018,11), frequency=12)

# Checking the Imported Data
BahrainNew_ts
cycle(BahrainNew_ts)
start(BahrainNew_ts)
end(BahrainNew_ts)
frequency(BahrainNew_ts)
head(BahrainNew_ts)
tail(BahrainNew_ts)
sum(is.na(BahrainNew_ts))
install.packages("forecast")
library(forecast)
BahrainNew_ts <- tsclean(BahrainNew_ts)
summary(BahrainNew_ts)
BahrainNew_ts

# Plotting the Time Series Data
plot(BahrainNew_ts)
plot(aggregate(BahrainNew_ts,FUN=mean))

# Decomposing
BahrainNew_ts_decomp <- decompose(BahrainNew_ts)
plot(BahrainNew_ts_decomp)

# Testing for Stationarity
install.packages("tseries")
library(tseries)
adf.test((BahrainNew_ts), alternative="stationary", k=0)

# To see any seasonal effect
boxplot(BahrainNew_ts~cycle(BahrainNew_ts))

# To remove trend effect
BahrainNew_ts_diff <- diff(BahrainNew_ts)
plot(BahrainNew_ts_diff)

# To remove variance effect
BahrainNew_ts_log <- log(BahrainNew_ts)
plot(BahrainNew_ts_log)

# To remove both (Trend and Variance) effects
BahrainNew_ts_both <- diff(log(BahrainNew_ts))
plot(BahrainNew_ts_both)

# Testing for Stationarity
# install.packages("tseries")
library(tseries)
adf.test(diff(log(BahrainNew_ts)), alternative="stationary",k=0)

# Dealing with ACF and PACF
# install.packages("tseries")
library(tseries)
acf(BahrainNew_ts)
acf(log(BahrainNew_ts))
acf(diff(BahrainNew_ts))
acf(diff(log(BahrainNew_ts)))
pacf(BahrainNew_ts)
pacf(log(BahrainNew_ts))
pacf(diff(BahrainNew_ts))
pacf(diff(log(BahrainNew_ts)))

# Observation
abline(reg=lm(BahrainNew_ts1~time(BahrainNew_ts)))

# Modelling
BahrainNew_ts_model <- auto.arima(BahrainNew_ts)
BahrainNew_ts_model
BahrainNew_ts_model <- auto.arima(BahrainNew_ts, ic="aic", trace = TRUE)
BahrainNew_ts_model

# Indicates the stationarity of the model
library(tseries)
plot.ts(BahrainNew_ts_model$resid)
acf(ts(BahrainNew_ts))
acf(ts(BahrainNew_ts_model$resid, main='ACF Residual'))
pacf(ts(BahrainNew_ts_model$resid, main='ACF Residual'))
           
# Forecasting
options(max.print=1000000)
install.packages("forecast")
# library(forecast)
BahrainNew_ts_forecast <- forecast (BahrainNew_ts_model, level=c(95), h=10*12)
plot(BahrainNew_ts_forecast)
BahrainNew_ts_forecast
             
# Validating the model
Box.test(BahrainNew_ts_model$resid, lag=5, type="Ljung-Box")
Box.test(BahrainNew_ts_model$resid, lag=10, type="Ljung-Box")
Box.test(BahrainNew_ts_model$resid, lag=15, type="Ljung-Box")
accuracy(BahrainNew_ts_forecast)
             